<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input v-model="searchKeyword" placeholder="搜索用户（账号/昵称/手机/邮箱）" clearable @clear="filterUsers"
        @keyup.enter="filterUsers">
        <template #append>
          <el-button @click="filterUsers">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 编辑对话框 -->
    <!-- 在模板中传递用户数据 -->
    <UserEditDialog ref="editDialogRef" :user-data="currentUser" @success="handleUpdateSuccess" />

    <!-- 用户表格 -->
    <el-table v-loading="loading" :data="filteredUsers" border stripe style="width: 100%">
      <!-- 头像列 -->
      <el-table-column label="头像" width="100" align="center">
        <template #default="{ row }">
          <el-avatar :size="50" :src="getAvatarUrl(row.avatar)" :fit="'cover'" class="user-avatar">
            <template #error>
              <div class="error-avatar">
                <el-icon>
                  <User />
                </el-icon>
              </div>
            </template>
          </el-avatar>
        </template>
      </el-table-column>

      <!-- 基础信息 -->
      <el-table-column prop="userName" label="账号" width="150" sortable />
      <el-table-column prop="nickName" label="昵称" width="150" sortable />
      <el-table-column prop="email" label="邮箱" min-width="200" />
      <el-table-column prop="phone" label="手机号" width="150" />

      <!-- 新增字段展示 -->
      <el-table-column label="性别" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getSexTagType(row.sex)">
            {{ getSexText(row.sex) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="生日" width="120">
        <template #default="{ row }">
          {{ formatDate(row.birthday) || '未设置' }}
        </template>
      </el-table-column>

      <el-table-column label="注册时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createdTime) }}
        </template>
      </el-table-column>

      <!-- 统计信息 -->
      <el-table-column label="帖子数" prop="postCount" width="100" sortable />
      <el-table-column label="关注数" prop="followingCount" width="100" sortable />
      <el-table-column label="粉丝数" prop="followerCount" width="100" sortable />

      <!-- 个人简介 -->
      <el-table-column label="个人简介" min-width="300">
        <template #default="{ row }">
          <div class="introduction">
            {{ row.introduction || '该用户暂未填写简介' }}
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsers } from '@/api/user'
import { getResourceUrl } from '@/utils/resource'
import dayjs from 'dayjs'
import UserEditDialog from '@/components/UserEditDialog.vue'

export default {
  components: {
    UserEditDialog
  },
  setup() {
    // 响应式数据
    const allUsers = ref([])
    const filteredUsers = ref([])
    const searchKeyword = ref('')
    const loading = ref(false)
    const editDialogRef = ref(null)
    const currentUser = ref({})

    // 性别显示映射
    const getSexText = (sex) => ['男', '女', '未知'][sex] || '未知'
    const getSexTagType = (sex) => ['', 'danger', 'info'][sex] || 'info'

    // 日期格式化
    const formatDate = (date) => date ? dayjs(date).format('YYYY-MM-DD') : ''
    const formatDateTime = (date) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : ''

    // 获取用户数据
    const fetchUsers = async () => {
      try {
        loading.value = true
        const res = await getUsers()
        allUsers.value = res.data.map(user => ({
          ...user,
          createdTime: dayjs(user.createdTime).format('YYYY-MM-DD HH:mm:ss'),
          birthday: user.birthday ? dayjs(user.birthday).format('YYYY-MM-DD') : null
        }))
        filteredUsers.value = [...allUsers.value]
      } catch (error) {
        ElMessage.error('获取用户数据失败')
      } finally {
        loading.value = false
      }
    }

    // 本地搜索过滤
    const filterUsers = () => {
      const keyword = searchKeyword.value.toLowerCase()
      filteredUsers.value = allUsers.value.filter(user =>
        Object.values(user).some(value =>
          String(value).toLowerCase().includes(keyword)
        )
      )
    }

    // 删除处理
    const handleDelete = async (userId) => {
      try {
        await ElMessageBox.confirm('确定删除该用户？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        filteredUsers.value = filteredUsers.value.filter(u => u.id !== userId)
        allUsers.value = allUsers.value.filter(u => u.id !== userId)
        ElMessage.success('删除成功')
      } catch (error) {
        console.log('删除操作已取消')
      }
    }

    // 编辑处理


    const handleEdit = (user) => {
      currentUser.value = user
      editDialogRef.value?.open()
    }

    // 刷新数据
    const handleUpdateSuccess = () => {
      fetchUsers()
    }

    // 初始化加载
    onMounted(fetchUsers)

    return {
      searchKeyword,
      filteredUsers,
      loading,
      editDialogRef,
      filterUsers,
      handleDelete,
      handleEdit,
      handleUpdateSuccess,
      getSexText,
      getSexTagType,
      formatDate,
      formatDateTime,
      currentUser,
    }
  },
  methods: {
    // 头像路径处理
    getAvatarUrl(avatarPath) {
      if (!avatarPath) return null
      try {
        const fileName = avatarPath
          .replace(/^[A-Z]:\\/i, '')
          .replace(/\\/g, '/')
          .split('/')
          .pop()
        return getResourceUrl(fileName)
      } catch (error) {
        console.error('头像路径解析错误:', error)
        return null
      }
    }
  }
}
</script>

<!-- 样式部分保持不变 -->
<style scoped>
.user-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.search-bar {
  margin-bottom: 20px;
  max-width: 500px;
}

.user-avatar {
  border: 1px solid #eee;
  background-color: #f5f7fa;
}

.error-avatar {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-avatar .el-icon {
  font-size: 24px;
  color: #909399;
}

.introduction {
  color: #666;
  font-size: 0.9em;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  margin: 2px;
}
</style>